package com.tuan.chi;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.location.Location;

import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.amap.mapapi.core.AMapException;
import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.core.PoiItem;
import com.amap.mapapi.location.LocationManagerProxy;
import com.amap.mapapi.location.LocationProviderProxy;
import com.amap.mapapi.map.*;
import com.amap.mapapi.poisearch.PoiPagedResult;
import com.amap.mapapi.poisearch.PoiSearch;
import com.amap.mapapi.poisearch.PoiTypeDef;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tuan.util.Constants;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 使用MyLocationOverlay实现地图自动定位
 * 实现初次定位使定位结果居中显示
 */
public class MyLocation extends MapActivity {
    private static final String TAG = "ASYNC_TASK";

    private MapView mMapView;
    private MapController mMapController;
    private GeoPoint point;
    private MyLocationOverlay mLocationOverlay;
    private PoiOverlay poiOverlay;
    private ProgressBar progressBar;
    private TextView myLocation;
    private int curpage = 1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMapView = (MapView) findViewById(R.id.mapView);
        myLocation = (TextView)  findViewById(R.id.TextViewSearch);
        mMapView.setBuiltInZoomControls(true);
        mMapController = mMapView.getController();
        point = new GeoPoint((int) (39.90923 * 1E6),
                (int) (116.397428 * 1E6));  //用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
        mMapController.setCenter(point);  //设置地图中心点
        mMapController.setZoom(15);
        mLocationOverlay = new MyLocationOverlay(this, mMapView);
        mMapView.getOverlays().add(mLocationOverlay);
        //实现初次定位使定位结果居中显示
        mLocationOverlay.runOnFirstFix(new Runnable() {
            public void run() {
                handler.sendMessage(Message.obtain(handler, Constants.FIRST_LOCATION));
            }
        });
    }

    @Override
    protected void onPause() {
        this.mLocationOverlay.disableMyLocation();
        super.onPause();
    }

    @Override
    protected void onResume() {
        this.mLocationOverlay.enableMyLocation();
        super.onResume();
    }


    class Task extends AsyncTask<String, Integer, PoiPagedResult> {

        //后台运行的方法 ,运行在非ui线程 可以执行耗时的操作
        @Override
        protected PoiPagedResult doInBackground(String... params) {

            try{
                String apiUrl = "http://api.dianping.com/v1/business/find_businesses";
                String appKey = "23589942";
                String secret = "692af39b47044e829c243307cfb2a42e";

                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put("latitude", String.valueOf(params[0]));
                paramMap.put("longitude", String.valueOf(params[1]));
                paramMap.put("offset_type", "1");
                paramMap.put("radius", "500");
                paramMap.put("limit", "20");


                GsonBuilder builder = new GsonBuilder();
                // 不转换没有 @Expose 注解的字段
                builder.excludeFieldsWithoutExposeAnnotation();
                Gson gson = builder.create();

                String requestResult = DemoApiTool.requestApi(apiUrl, appKey, secret, paramMap);

                dianping_find_businesses_SearchResult Result = gson.fromJson(requestResult, dianping_find_businesses_SearchResult.class);

                if (Result.getStatus().equals("OK")) {
                    int total = Result.getCount();
                    int count = 0;
                    while (count<total) {
                        count ++;
                        //调用publishProgress公布进度,最后onProgressUpdate方法将被执行
                        publishProgress((int) ((count / (float) total) * 100));
                        //为了演示进度,休眠500毫秒
                      //  Thread.sleep(500);
                    }
                    List<dianping_businesses_Result> Businesses_Result=Result.getBusinesses();
                    String Address=Businesses_Result.get(0).getAddress();
                    String Name=Businesses_Result.get(0).getName();
                    PoiSearch poiSearch= new PoiSearch(MyLocation.this,new PoiSearch.Query(Address+" "+Name , PoiTypeDef.All, "0571")); // "010为北京电话区号"
                    PoiPagedResult result = poiSearch.searchPOI();

                    return result;
                }
            } catch(Exception e) {
                e.printStackTrace();

            }

            return null;

        }

        // 运行在主线程中,ui线程中, 在doInbackground执行完毕后执行
        @Override
        protected void onPostExecute(PoiPagedResult result) {
            // 返回HTML页面的内容
           // myLocation.setText(result);
            List<PoiItem> poiItems = null;
            try {
                poiItems = result.getPage(curpage);
                if (poiItems != null && poiItems.size() > 0) {
                    mMapController.setZoom(13);
                    mMapController.animateTo(poiItems.get(0).getPoint());
                    if (poiOverlay != null) {
                        poiOverlay.removeFromMap();
                    }
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.da_marker_red);
                    poiOverlay = new PoiOverlay(drawable, poiItems);
                    poiOverlay.addToMap(mMapView); // 将poiOverlay标注在地图上
                    poiOverlay.showPopupWindow(0);
                    mMapView.invalidate();
                }
            } catch (AMapException e) {

            }

        }

        //运行在ui线程中 ,在调用 doInbackground方法之前执行,
        @Override
        protected void onPreExecute() {
            // 任务启动，可以在这里显示一个对话框，这里简单处理
            Log.i(TAG, "onPreExecute() called");
            myLocation.setText("loading...");
        }

        //在调用publishProgress(Progress... values)时，此方法被执行，直接将进度信息更新到UI组件上。
        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
         // progressBar.setProgress(values[0]);
            myLocation.setText("loading..." + values[0] + "%");
        }

    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == Constants.FIRST_LOCATION) {
                mMapController.animateTo(mLocationOverlay.getMyLocation());
                int geoLat = mLocationOverlay.getMyLocation().getLatitudeE6();
                int geoLng = mLocationOverlay.getMyLocation().getLongitudeE6();
                myLocation.setText("定位成功:("  + geoLng + "," + geoLat + ")");

                Task task = new Task();
                String[] point={ String.valueOf(geoLat/1E6),String.valueOf(geoLng/1E6)};
                task.execute(point);


            }
        }
    };


}